<template>
  <div class="login-form">
    <el-form ref="ruleFormRef" style="width: 400px" :model="ruleForm" status-icon :rules="rules" label-width="auto"
      class="login-ruleForm">
      <el-form-item label="用户名" prop="username">
        <el-input v-model="ruleForm.username" autocomplete="off" />
      </el-form-item>
      <el-form-item label="密码" prop="pass">
        <el-input v-model="ruleForm.pass" type="password" autocomplete="off" />
      </el-form-item>
      <el-form-item class="operate-item">
        <el-button type="primary" @click="submitForm(ruleFormRef)">
          登录
        </el-button>
        <el-button @click="resetForm(ruleFormRef)">重置</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script lang="ts" setup>
import { login as loginApi } from "@/api/user";
import pinia from "@/store";
import { useAppStore } from "@/store/modules/app";
import { setLocalStorage } from "@/utils/utils";
import type { FormInstance, FormRules } from "element-plus";
import { reactive, ref } from "vue";
import { useRouter } from "vue-router";

const appStore = useAppStore(pinia);

const router = useRouter();
const ruleFormRef = ref<FormInstance>()

const login = () => {
  loginApi({
    username: ruleForm.username,
    password: ruleForm.pass
  }).then((res) => {
    if (res) {
      const { token, username } = res.data
      setLocalStorage("token", token);
      appStore.saveUserInfo({ username });
      router.push("/home");
    }
  })
}

const validatePass = (rule: any, value: any, callback: any) => {
  if (value === "") {
    callback(new Error("Please input the password"))
  } else {
    // if (ruleForm.username !== "") {
    //   if (!ruleFormRef.value) return
    //   ruleFormRef.value.validateField("checkPass")
    // }
    callback()
  }
}
const validateUsername = (rule: any, value: any, callback: any) => {
  if (value === "") {
    callback(new Error("Please input the username"))
  } else {
    callback()
  }
}

const ruleForm = reactive({
  pass: "123",
  username: "zs",
})

// @ts-ignore
const rules = reactive<FormRules<typeof ruleForm>>({
  pass: [{ validator: validatePass, trigger: "blur" }],
  username: [{ validator: validateUsername, trigger: "blur" }],
})

const submitForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.validate((valid) => {
    if (valid) {
      console.log("submit!")
      login();
    } else {
      console.log("error submit!")
    }
  })
}

const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.resetFields()
}
</script>
<style scoped lang="scss">
.login-form {
  height: 100vh;
  display: flex;
  justify-content: center;
  align-items: center;

  .login-ruleForm {
    .operate-item {
      ::v-deep .el-form-item__content {
        display: flex;
        justify-content: space-between;
      }
    }
  }
}
</style>
